/*
 * @Author: Administrator
 * @Date:   2018-01-05 08:39:35
 * @Last Modified by:   Administrator
 * @Last Modified time: 2018-01-09 16:01:56
 */
import {
  observable,
  action,
  toJS,
} from 'mobx'
import { objToStrMap } from '../util/comm'
import getArcDetail from '../request/get_arc_detail';
import { cancelRequest } from '../request/fetch'

// 技术文章
class RD {
  constructor(initialState) {
    if (initialState && initialState.rd && initialState.rd.article) {
      this.article = objToStrMap(initialState.rd.article)
    } else {
      this.article = new Map()
    }
  }
  @observable article
  @action getRd(arcId) {
    return new Promise((resolve, reject) => {
      const key = `article${arcId}`
      if (this.article.get(key)) {
        resolve(this.article.get(key))
      }
      // 请求数据
      getArcDetail(arcId).then((res) => {
        if (res.status === 200) {
          let resArticle
          for (const article of res.data) {
            const {
              title,
              author,
              content,
              date,
              categories,
            } = article
            resArticle = {
              title,
              author,
              content,
              date,
              categories,
            }
          }
          this.article.set(key, resArticle)
          resolve(resArticle)
        } else {
          reject(res.data)
        }
      }).catch(reject)
    })
  }
  toJson() {
    return {
      article: toJS(this.article),
    }
  }
  cancel() {
    cancelRequest();
  }
}
export default RD
